//index.js
//获取应用实例
var util= require("../../../utils/util.js");
var app = getApp()
Page({
  data: {
    tabs: [
      {title: '待使用', },
      {title: '已使用',},
      {title: '已失效', },
      
    ]
  ,
   
    tabClass: ["", ""],
    coupons:[]
  },
  onLoad: function () {
  },
  //切换状态
  onClick: function(e) {
    var that = this;
    that.setData({
      coupons: [],
    });
  ///  console.log(`ComponentId:${e.detail.componentId},you selected:${e.detail.key}`);
   
    this.getMyCoupons(e.detail.key);
  },
  onShow : function () {
    let type = 0
    
    if(wx.getStorageSync('userid')){
      this.getMyCoupons(type);
  }else{
    wx.showModal({
      title: '提示',
      content: '您的操作需要登录',
      showCancel: false
    })
   
  }
   
  },
  getMyCoupons: function (type) {
    var that = this;
    const db = wx.cloud.database()
    const _ =db.command
    let where ={}
   if(type==0){
     where ={
        _openid:wx.getStorageSync('openid'),
        dateEnd : _.gt(new Date()),
        status :0
     }
   }else if(type==1){
    where ={
      _openid:wx.getStorageSync('openid'),
      status :1
    }
    }
    else if(type==2){
      where ={
        _openid:wx.getStorageSync('openid'),
        dateEnd : _.lt(new Date()),
        status :0
      }
    }
    db.collection('coupons').where(where).get({
      success: res => {
        if (res.data.length > 0) {
          var coupons = res.data;
          for (let index = 0; index < coupons.length; index++) {
            var element = coupons[index];
            if(element.dateEnd<new Date()){
              element.status=2
            }
            element.dateEnd = util.formatTime(element.dateEnd )
          }
        //  console.log(coupons)
          if (coupons.length > 0) {
            that.setData({
              coupons: coupons,
            });
          }
        
        }else{
          that.setData({
            coupons: null,
          });
        }
      }
    })
  },
  goBuy:function(){
    wx.reLaunch({
      url: '/pages/classification/index'
    })
  }

})
